// pages/orderPay/orderPay.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var pay = require("../../../services/pay");
let num = 0;
const App = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        wxAddress:null,
        isMail:false,
        isGroupBuying:false,
        imageIconList: {
            promise: "/static/images/orderpay/promise.png",
            bags: "/static/images/orderpay/bags.png",
            moreGray: "/static/images/orderpay/more-gray.png",
            moreRed: "/static/images/orderpay/more-red.png",
        },
        showDialog: false,
        nextDate: null,
        commodityList: {}, //购买商品
        exchangeCommodityList: [], //换购商品
        selectedExchangeList: [], //已选中的换购商品
        payAmount: 0,
        scoreAmount: 0, 
        totalAmount: 0,
        savingAmount: 0,
        couponAmount: 0,
        isCreatingOrder: false, //防重复触碰支付装置
        memberLeaderObj: {},
        userInfo: {},
        disabledBtn: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const date = new Date();
        date.setDate(date.getDate()+1);
        const nextDate = util.formatTime(date.getTime() / 1000,'Y-M-D');
        const userInfo = wx.getStorageSync("userInfo");
        this.setData({
            nextDate,
            userInfo
        });
        //this.getPreOrder();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const orderGoodsList = wx.getStorageSync("orderGoodsList");
        let discountPrice = (orderGoodsList.savingPrice * orderGoodsList.quantity).toFixed(2)
        this.setData({
            commodityList:orderGoodsList,
            discountPrice:discountPrice
        })
        let wxAddress = wx.getStorageSync('wxAddress');
        if(wxAddress){
            this.setData({
                wxAddress:wxAddress
            })
        }
        this.setData({
            memberLeaderObj: App.globalData.memberLeaderObj
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 关闭优惠的弹窗
    dialogClose(){
        this.setData({
            showDialog: false
        })
    },
    dialogBuy(e){
        console.log("e", e.detail);
        const { isClose, item } = e.detail;
        this.setData({
            showDialog: false,
            selectedExchangeList: [item]
        })
        console.log("null", num++);
        this.getPreOrder(true);
    },
    // 确认订单信息
    getPreOrder(isSelectedExchange = false){
        const data = this.getOrderParams();
        util.request(api.orderUrl.preOrder, data, "POST").then((res) =>{
            console.log("res", res);
            const data = res.result;
            //let showDialog = false;
            //if(data.exchangeCommodityList.length && !isSelectedExchange){
                //showDialog = true
            //}
            this.setData({
                commodityList: data.commodityList,
                exchangeCommodityList: data.exchangeCommodityList,
                payAmount: data.payAmount,
                scoreAmount: data.scoreAmount,
                totalAmount:data.totalAmount,
                savingAmount: data.savingAmount,
                couponAmount: data.couponAmount
            })
        })
    },
    // 确认订单和创建订单参数
    getOrderParams(params){
        let wxAddress = this.data.wxAddress
        let commodityList = this.data.commodityList
        let address = wxAddress.provinceName+''+wxAddress.cityName+wxAddress.countyName+wxAddress.detailInfo+wxAddress.userName+" 电话："+wxAddress.telNumber
        let defaultParams = {
            commodityId:commodityList.commodityId,
            payType: commodityList.payType,
            price:commodityList.wholesalerPrice * commodityList.quantity,
            sum: commodityList.quantity,
            wechatAddress:address
        };
        return Object.assign(defaultParams, params);
    },
    // 创建订单
    createOrder(){
        let _this = this
        if(!this.data.wxAddress){
            return wx.showToast({
                title: "请先选择邮寄地址",
                icon: "none"
            });
        }
        if(this.data.isCreatingOrder){
            return wx.showToast({
                title: "正在创建",
                icon: "loading"
            });
        }
        this.setData({
            isCreatingOrder: true,
            disabledBtn: true
        })
        const data = this.getOrderParams();
        util.request(api.wholesaler.orderCreate, data, "POST").then((ress) =>{
            //console.log(ress);
            _this.setData({
                isCreatingOrder: false,
            })
            if(ress.result){
                util.request(api.wholesaler.orderPay,{orderId:ress.result},'put').then(res=>{
                    if(res.result){
                        wx.requestPayment({
                            'timeStamp': res.result.timeStamp,
                            'nonceStr': res.result.nonceStr,
                            'package': res.result.packageValue,
                            'signType': res.result.signType,
                            'paySign': res.result.paySign,
                            'success': function (res) {
                                _this.setData({
                                    disabledBtn:false
                                })
                                wx.hideLoading()
                                wx.navigateTo({
                                    url: '/pages/wholesalers/orderResult/orderResult',
                                })
                            },
                            'fail': function (res) {
                                wx.hideLoading()
                                wx.showToast({
                                    title: "支付失败",
                                    icon: "none"
                                })
                                _this.setData({
                                    disabledBtn:false
                                })
                            },
                            'complete': function (res) {
                              reject(res);
                            }
                        });
                    }else {
                        wx.navigateTo({
                            url: "/pages/wholesalers/orderResult/orderResult"
                        })
                    }
                    
                }).catch(err=>{
                    console.log(err)
                    wx.showToast({
                      title: '购买失败，请重新购买～',
                    })
                    wx.hideLoading()
                    this.setData({
                        disabled:false
                    })
                })
            } 
            
        })
    },
    getWxAddress(){
        wx.getSetting({
            success: (result)=>{
            const scopeAddress = result.authSetting["scope.address"]
            if(scopeAddress===true||scopeAddress===undefined){
                wx.chooseAddress({
                    success: (result)=>{
                        wx.setStorageSync('wxAddress', result)
                        this.setData({
                            wxAddress:result
                        })
                    },
                });
            }
            else{
                wx.openSetting({
                    success:(result)=>{
                        console.log(result)
                    }
                })
            }
            }
        });
    }
});
